/**
 * https://leetcode-cn.com/problems/contains-duplicate-ii/
 * 存在重复元素II
 * @param nums 
 * @param k 
 */
const containsNearbyDuplicate = (nums: number[], k: number): boolean => {
    const len = nums.length;
    const set = new Set<number>()

    for (let i = 0; i < len; i++) {
        // 存在相同的
        if (set.has(nums[i])) {
            return true
        }

        set.add(nums[i])

        // k个了还没找到, 删掉旧的
        if (i >= k) {
            set.delete(nums[i - k])
        }
    }

    return false
};


const containsNearbyDuplicate2 = (nums: number[], k: number): boolean => {
    const len = nums.length;
    const map: Record<number, number> = {}

    for (let i = 0; i < len; i++) {
        let prev = map[nums[i]]
        // 存在该值
        if (prev !== undefined) {
            if (i - prev <= k) return true
        }

        // 赋值为当前索引
        map[nums[i]] = i
    }


    return false
};